package com.easyweb.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class FileUtils {
	
	private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
	/**
	 * 上传文件
	 * @param request
	 * @param path
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static List<String> uploadFile(HttpServletRequest request,String path) throws IllegalStateException, IOException{
		List<String> files = new ArrayList<String>();
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
                //记录上传过程起始时的时间，用来计算上传时间  
                int pre = (int) System.currentTimeMillis();
                logger.info("文件上传开始...");
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    logger.info("文件名:"+myFileName);
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        //重命名上传后的文件名  
                        String fileName = EncryptUtils.md5(myFileName.substring(0, myFileName.lastIndexOf("."))+new Date().getTime());  
                        if(!StringUtils.isEmpty(myFileName)){
                        	fileName = fileName+myFileName.substring(myFileName.lastIndexOf("."));
                        	//定义上传路径    
                            File localFile = new File(path+fileName);  
                            File dir = new File(path);
                            if(!dir.exists()){
                            	dir.mkdirs();
                            }
                            if(!localFile.exists()){
                            	localFile.createNewFile();
                            }
                            file.transferTo(localFile);
                            files.add(fileName);
                        }
                    }  
                }  
                //记录上传该文件后的时间  
                int finaltime = (int) System.currentTimeMillis();
                logger.info("文件上传结束，用时"+(finaltime - pre)+"ms");
            }  
              
        }
        return files;
	}
	/**
	 * 删除文件
	 * @param path
	 */
	public static void deleteFile(String path){
		File file = new File(path);
		if(file.exists()){
			try {
				file.delete();
				logger.info("文件删除成功！文件路径："+path);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("文件删除失败："+e.getMessage());
			}
		}
	}
}
